#import "DNAViewOld.h"
#import "ExtraCategories.h"



@implementation DNAViewOld


//	Each property of an object can be animated in different ways, so an array of animations is built up and consulted
//	when performing an animation.   Typical built in animatable properties may include a views origin, frame, or alpha.
//	In this case we extend the dictionary by adding animations for "speed", "curvature", and "ticks" properties.
//	Whenever animations on these properties are performed we return theanimation type "CABasicAnimation".  More complex
//	animations such as "CAKeyframeAnimation" could be used for other properties.
+ (id)defaultAnimationForKey:(NSString *)key {
	
    if ([key isEqualToString:@"speed"] || [key isEqualToString:@"curvature"] || [key isEqualToString:@"ticks"]) {
        return [CABasicAnimation animation];
    } else {
        return [super defaultAnimationForKey:key];
    }
}
- (void) setupRenderTimer
{
	NSTimeInterval timeInterval = 0.1;
	
	myDrawTimer = [ [ NSTimer scheduledTimerWithTimeInterval:timeInterval
													  target:self
													selector:@selector( drawMe: )
													userInfo:nil repeats:YES ] retain ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSEventTrackingRunLoopMode ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSModalPanelRunLoopMode ];
}
- (BOOL) acceptsFirstResponder
{
	return YES;
}
- (id) managedObjectModel
{
	id highlightDocument = [myDocController currentDocument];
	return [highlightDocument managedObjectModel];
}
- (id) managedObjectContext
{
	id highlightDocument = [myDocController currentDocument];
	return [highlightDocument managedObjectContext];
}

- (void) awakeFromNib
{

	mouseScrollX = 0;
	mouseScrollY = 0;
	
	myDocController = [NSDocumentController sharedDocumentController];
	myDocs = [myDocController documents];
	
	myDrawTimer = nil;
	[ self setupRenderTimer ];
	initialSetupFinished = NO;// Not finished Setting up yet
	drawItemsList = [[NSMutableArray alloc] init];
	myBundle	= [NSBundle mainBundle];
	myAppPath	= [myBundle bundlePath];
	myAppFolderPath	= [myAppPath stringByDeletingLastPathComponent];
	myDataFolderPath	= [myAppFolderPath stringByAppendingPathComponent: @"data"];
	
	entities = [managedObjectModel entitiesByName];
	
	uceEntity = [entities valueForKey:@"UCE"];
	ncuEntity = [entities valueForKey:@"NeurosporaCrassaUniqueIdentifier"];
	cddEntity = [entities valueForKey:@"ConservedProteinDomainDatabase"];
	blocksEntity = [entities valueForKey:@"Blocks"];
	
	ncuSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	ncuSortDescriptors = [NSArray arrayWithObject: ncuSort];
	ncuFetch = [[NSFetchRequest alloc] init];
	[ncuFetch setEntity: ncuEntity];
	[ncuFetch setSortDescriptors: ncuSortDescriptors];
	
	cddSort = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	cddSortDescriptors = [NSArray arrayWithObject: cddSort];
	cddFetch = [[NSFetchRequest alloc] init];
	[cddFetch setEntity: cddEntity];
	[cddFetch setSortDescriptors: cddSortDescriptors];
	
	uceSort = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	uceSortDescriptors = [NSArray arrayWithObject: uceSort];
	uceFetch = [[NSFetchRequest alloc] init];
	[uceFetch setEntity: uceEntity];
	[uceFetch setSortDescriptors: uceSortDescriptors];
	
	blocksSort = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	blocksSortDescriptors = [NSArray arrayWithObject: blocksSort];
	blocksFetch = [[NSFetchRequest alloc] init];
	[blocksFetch setEntity: blocksEntity];
	[blocksFetch setSortDescriptors: blocksSortDescriptors];
	
	//NSLog(@"DNAView: %i,%i,%i,%i",[myNCUs count],[myBlocks count],[myCDDs count],[myUCEs count]);
}


- (id)initWithFrame:(NSRect)frameRect {
	if ((self = [super initWithFrame:frameRect]) != nil) {
		//[self setSpeed: 65.0];
		//[self setCurvature: 60.0];
		//[self setTicks: 11];
	}
	return self;
}


float	Pin( float min, float max, float value ) {
	if (value < min)		return(min);
	else if (value > max)	return(max);
	else					return(value);
}

- (float)speed {
    return speed;
}

- (void)setSpeed:(float)value {
	float nextSpeed	= Pin( 0, 100, value);
	
    if (speed != nextSpeed) {
        speed = nextSpeed;
		[self setNeedsDisplay:YES];
    }
}


- (float)curvature {
    return curvature;
}

- (void)setCurvature:(float)value {
	float nextCurvature	= Pin( 0, 100, value);
	
	if (curvature != nextCurvature) {
        curvature = nextCurvature;
		[self setNeedsDisplay:YES];
    }
}


- (int)ticks {
    return ticks;
}


- (void)setTicks:(float)value {
	int nextTicks	= (int) Pin( 3, 21, value);
	
    if (ticks != nextTicks) {
        ticks = nextTicks;
		[self setNeedsDisplay:YES];
    }
}


- (void)saveSweepWithCenter:(NSPoint) centerPt startAngle:(float) stAngle endAngle:(float) enAngle {
	iStartAngle = stAngle; /* degrees counter clockwise from the x axis */
	iEndAngle = enAngle; /* degrees counter clockwise from the x axis */
	iCenterPt = centerPt; /* pivot point */
}


- (NSBezierPath*) speedPointerPath {
	NSBezierPath* speedPointer = [NSBezierPath bezierPath];
	[speedPointer moveToPoint:NSMakePoint(134.39, 218.05)];
	[speedPointer curveToPoint:NSMakePoint(137.95, 219.75)
					   controlPoint1:NSMakePoint(134.39, 218.05)
					   controlPoint2:NSMakePoint(137.95, 219.75)];
	[speedPointer curveToPoint:NSMakePoint(141.78, 357.55)
					   controlPoint1:NSMakePoint(137.95, 219.75)
					   controlPoint2:NSMakePoint(141.78, 357.55)];
	[speedPointer curveToPoint:NSMakePoint(151.13, 356.31)
					   controlPoint1:NSMakePoint(141.78, 357.55)
					   controlPoint2:NSMakePoint(145.39, 359.54)];
	[speedPointer curveToPoint:NSMakePoint(158.95, 349.86)
					   controlPoint1:NSMakePoint(156.87, 353.08)
					   controlPoint2:NSMakePoint(158.95, 349.86)];
	[speedPointer curveToPoint:NSMakePoint(134.49, 415.99)
					   controlPoint1:NSMakePoint(158.95, 349.86)
					   controlPoint2:NSMakePoint(134.49, 415.99)];
	[speedPointer curveToPoint:NSMakePoint(110.02, 349.86)
					   controlPoint1:NSMakePoint(134.49, 415.99)
					   controlPoint2:NSMakePoint(110.02, 349.86)];
	[speedPointer curveToPoint:NSMakePoint(117.84, 356.31)
					   controlPoint1:NSMakePoint(110.02, 349.86)
					   controlPoint2:NSMakePoint(112.1, 353.08)];
	[speedPointer curveToPoint:NSMakePoint(127.19, 357.55)
					   controlPoint1:NSMakePoint(123.58, 359.54)
					   controlPoint2:NSMakePoint(127.19, 357.55)];
	[speedPointer curveToPoint:NSMakePoint(131.02, 219.75)
					   controlPoint1:NSMakePoint(127.19, 357.55)
					   controlPoint2:NSMakePoint(131.02, 219.75)];
	[speedPointer curveToPoint:NSMakePoint(134.39, 218.05)
					   controlPoint1:NSMakePoint(131.02, 219.75)
					   controlPoint2:NSMakePoint(134.39, 218.05)];
	[speedPointer closePath];
	[speedPointer setLineJoinStyle:NSRoundLineJoinStyle];
	[speedPointer setLineCapStyle:NSRoundLineCapStyle];
	[speedPointer setLineWidth: 0.25];
	return speedPointer;
}

- (NSBezierPath*) ornamentPath {
	NSBezierPath* ornament = [NSBezierPath bezierPath];
	[ornament moveToPoint:NSMakePoint(0, 0)];
	[ornament lineToPoint:NSMakePoint(0, 30.0)];
	[ornament lineToPoint:NSMakePoint(20.0, 30.0)];
	[ornament lineToPoint:NSMakePoint(10, 35.0)];
	[ornament lineToPoint:NSMakePoint(30, 27.5)];
	[ornament lineToPoint:NSMakePoint(10.0, 20.0)];
	[ornament lineToPoint:NSMakePoint(20.0, 25.0)];
	[ornament lineToPoint:NSMakePoint(5.0, 25.0)];
	[ornament lineToPoint:NSMakePoint(5.0, 0.0)];
	[ornament closePath];
	[ornament setLineJoinStyle:NSRoundLineJoinStyle];
	[ornament setLineCapStyle:NSRoundLineCapStyle];
	[ornament setLineWidth: 1.0];	
	return ornament;
}



/* this method returns the NSBezierPath that we will
 used for the tick marks around the outside of the view. */
- (NSBezierPath*) tickMarkPath {
	NSBezierPath* tickMark = [NSBezierPath bezierPath];
	
	
	[tickMark moveToPoint:NSMakePoint(0, 0)];
	[tickMark lineToPoint:NSMakePoint(0, 30.0)];
	[tickMark lineToPoint:NSMakePoint(20.0, 30.0)];
	[tickMark lineToPoint:NSMakePoint(10, 35.0)];
	[tickMark lineToPoint:NSMakePoint(30, 27.5)];
	[tickMark lineToPoint:NSMakePoint(10.0, 20.0)];
	[tickMark lineToPoint:NSMakePoint(20.0, 25.0)];
	[tickMark lineToPoint:NSMakePoint(5.0, 25.0)];
	[tickMark lineToPoint:NSMakePoint(5.0, 0.0)];
	
	
	[tickMark closePath];
	[tickMark setLineJoinStyle:NSRoundLineJoinStyle];
	[tickMark setLineCapStyle:NSRoundLineCapStyle];
	[tickMark setLineWidth: 0.25];
	return tickMark;
}

- (void) populateDrawItems
{
	if ([[NCUController selectedObjects] count]){
		int i;
		drawItemsList = [[NSMutableArray alloc] init];
		NSAffineTransform* transform = [NSAffineTransform transform];
		NSAffineTransform* identity = [NSAffineTransform transform];		
		
		for (i=0; i < 10; i++)
		{
			id currentNCU = [[NCUController selectedObjects] objectAtIndex:0];
			[transform initWithTransform: identity]; 
			
			[transform translateXBy:100 yBy:10];
			[transform concat];
			
			NSString *nameLabel = [currentNCU valueForKey:@"name"];
			NSFont* nameFont = [[NSFont labelFontOfSize:14] printerFont];
			NSBezierPath* namePath = [nameLabel bezierWithFont: nameFont];
			//[namePath transformUsingAffineTransform: 
			// [[NSAffineTransform transform]
			//  scaleBounds: [namePath bounds]
			//  toHeight: 0
			//  centeredAboveOrigin: 10]];
			
			[[NSColor blueColor] set];
			[namePath fillWithShadowAtDegrees:90 withDistance: 10];
			[[NSColor lightGrayColor] set];

			id ncuNameBox = namePath;
			//id ncuRulerBox = namePath;

			//Name array add
			[drawItemsList addObject:
			 [NSArray arrayWithObjects:
			  ncuNameBox,
			  nameLabel
			  ]
			 ];
			//Ruler array add
			/*[drawItemsList addObject:
			 [NSArray arrayWithObjects:
			  ncuRulerBox,
			  [currentNCU valueForKey:@"proteinSequence"]
			  ]
			 ];
			
			//[drawItemsList addObject:];
			*/
			[NCUController selectNext:self];
		}
		initialSetupFinished = YES;	
	}
}

static inline float DEGREES_TO_RADIANS(float degrees){
    return degrees * M_PI/180;
}

static CGColorSpaceRef myGetGenericRGBSpace(void)
{
    // Only create the color space once.
    static CGColorSpaceRef colorSpace = NULL;
    if ( colorSpace == NULL ) {
		colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    }
    return colorSpace;
}

static CGColorRef myGetBlueColor(void)
{
    // Only create the CGColor object once.
    static CGColorRef blue = NULL;
    if(blue == NULL){
		// R,G,B,A
		float opaqueBlue[4] = { 0, 0, 1, 1 };
		blue = CGColorCreate(myGetGenericRGBSpace(), opaqueBlue);
    }
    return blue;
}

static CGColorRef myGetGreenColor(void)
{
    // Only create the CGColor object once.
    static CGColorRef green = NULL;
    if(green == NULL){
		// R,G,B,A
		float opaqueGreen[4] = { 0, 1, 0, 1 };
		green = CGColorCreate(myGetGenericRGBSpace(), opaqueGreen);
    }
    return green;
}

static CGColorRef myGetRedColor(void)
{
    // Only create the CGColor object once.
    static CGColorRef red = NULL;
    if(red == NULL){
		// R,G,B,A
		float opaqueRed[4] = { 1, 0, 0, 1 };
		red = CGColorCreate(myGetGenericRGBSpace(), opaqueRed);
    }
    return red;
}


/* custom view's main drawing method */
- (void)drawRect:(NSRect)rect {

	/*
	if (!initialSetupFinished)
	{
		[self populateDrawItems];
		[self setNeedsDisplay:YES];
	}
	*/
	myDocController = [NSDocumentController sharedDocumentController];
	id highlightDocument = [myDocController currentDocument];

	managedObjectModel = [highlightDocument managedObjectModel];
	managedObjectContext = [highlightDocument managedObjectContext];
//	NSLog(@"your de%@",[managedObjectContext description]);

	
	NSPoint pt;
    pt = [[NSApp mainWindow] mouseLocationOutsideOfEventStream];
	
	pt = [self convertPoint:pt fromView:nil];
	pt.x -= mouseScrollX;
	pt.y -= mouseScrollY -2;
	// dj roots suriso de flor
	id NCUblocks = [[BlocksController arrangedObjects] sortedArrayUsingDescriptors:blocksSortDescriptors];
	id NCUcdd = [[CDDController arrangedObjects] sortedArrayUsingDescriptors:cddSortDescriptors ];
	id NCUuce = [[UCEController arrangedObjects] sortedArrayUsingDescriptors:uceSortDescriptors ];
	id NCUcluster = [[ClusterController arrangedObjects] sortedArrayUsingDescriptors:uceSortDescriptors ];
	
	//NSLog(@"your de%@",[NCUblocks description]);

	//NSLog(@"Cluster = %i",[[ClusterController arrangedObjects] count]);
	
	NSRect boundary = [self bounds];
	
	const float shadowAngle = -35.0;
	NSPoint center;
	
	center.x = boundary.origin.x + (boundary.size.width/2.0);
	center.y = boundary.origin.y + (boundary.size.height/2.0);
	
	float dnaShadow = 5.0;
	float topLineOffsetx = 20.0;
	float seqSizeX = boundary.size.width - topLineOffsetx;
	float seqSizeY = boundary.size.height/2.0;
	
	// START CODON ARROW
	float NCULength = 0; 
	if ([[NCUController selectedObjects] count] > 0)
		NCULength = (float)[[[[NCUController selectedObjects] objectAtIndex:0] valueForKey:@"proteinSequence"] length];


	
	int k;
	/*for (k=0; k<[NCUcluster count]; k++)
	{
		
		int startME = [[[NCUcluster objectAtIndex:k] valueForKey:@"protStart"] intValue];
		int stopME = [[[NCUcluster objectAtIndex:k] valueForKey:@"protEnd"] intValue];
		///************************************************************
		NSBezierPath* clusterSequenceRect = [[[NSBezierPath alloc] init] autorelease];
		[clusterSequenceRect appendBezierPathWithRoundedRect:
		 NSMakeRect(startME, 0, stopME, boundary.size.height) xRadius:2.5 yRadius:2.5];
		[clusterSequenceRect closePath];
		[clusterSequenceRect setLineJoinStyle:NSRoundLineJoinStyle];
		NSColor *clusterBackgroundColor;
		if ([clusterSequenceRect containsPoint:pt])
		{
			[NCUTextView setSelectedRange:NSMakeRange(0,NCULength)];
			[clusterSequenceRect setLineWidth: 1.5];
			clusterBackgroundColor = [NSColor colorWithCalibratedRed:1 green:1 blue:0.1 alpha: 0.7];

		}
		else
		{	
			[clusterSequenceRect setLineWidth: 0.5];
			clusterBackgroundColor = [NSColor colorWithCalibratedRed:1 green:1 blue:0.8 alpha: 0.4];			
		}
		

		//NSGradient *clusterBackgroundGradient = [[NSGradient alloc]
		//										 initWithColorsAndLocations:
		//										 [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
		//										 clusterBackgroundColor, 0.7, clusterBackgroundColor, 1.0,  
		//										 nil];
		
		
		//[clusterSequenceRect fillWithShadowAtDegrees:shadowAngle withDistance: dnaShadow];
		
		//NSPoint clusterGradientCenter = 
		//[[[NSAffineTransform transform]
		//mapFrom:[clusterSequenceRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
		//[clusterBackgroundGradient drawInBezierPath: clusterSequenceRect relativeCenterPosition: clusterGradientCenter];
		[clusterBackgroundColor set];
		[clusterSequenceRect fill];
		[clusterSequenceRect stroke];
		
	}
	*/


	NSBezierPath* ornament = [self ornamentPath];
	
	id transform = [NSAffineTransform transform];
	id identity = [NSAffineTransform transform];
	
	[transform translateXBy:topLineOffsetx+mouseScrollX yBy:center.y+mouseScrollY];
	[transform concat];
	
	[ornament transformUsingAffineTransform: 
	 [transform
	  scaleBounds: [ornament bounds]
	  toHeight: 25
	  centeredAboveOrigin: 0]];	
	NSGradient *ornamentGradient = [[NSGradient alloc]
									initWithStartingColor: [NSColor greenColor]
									endingColor: [NSColor whiteColor]];
	[ornamentGradient drawInBezierPath:ornament angle:90];
	[ornamentGradient release];
	[[NSColor greenColor] set];
	[ornament stroke];
//	id theCluster = [[[[NCUController selectedObjects] objectAtIndex:0] mutableSetValueForKey:@"cluster"] anyObject];
	
	[transform initWithTransform:identity];
	[transform translateXBy:-topLineOffsetx yBy:-center.y];
	[transform concat];	
	
	NSBezierPath* dnaSequenceRect = [[[NSBezierPath alloc] init] autorelease];
	[dnaSequenceRect appendBezierPathWithRoundedRect:
	 NSMakeRect(topLineOffsetx/2.0, seqSizeY, seqSizeX, 4) xRadius:2.5 yRadius:2.5];
	[dnaSequenceRect closePath];
	[dnaSequenceRect setLineJoinStyle:NSRoundLineJoinStyle];
	if ([dnaSequenceRect containsPoint:pt])
	{
		[NCUTextView setSelectedRange:NSMakeRange(0,NCULength)];
		[dnaSequenceRect setLineWidth: 1.5];
	}
	else
		[dnaSequenceRect setLineWidth: 0.5];
	
	NSColor *newBackgroundColor = [NSColor colorWithCalibratedRed:.45 green:.43 blue:8.0 alpha: 1.0];
	NSGradient *newBackgroundGradient = [[NSGradient alloc]
									  initWithColorsAndLocations:
									  [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
									  newBackgroundColor, 0.7, newBackgroundColor, 1.0,  
									  nil];
	
	
	[dnaSequenceRect fillWithShadowAtDegrees:shadowAngle withDistance: dnaShadow];

	NSPoint newGradientCenter = 
	[[[NSAffineTransform transform]
	  mapFrom:[dnaSequenceRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
	[newBackgroundGradient drawInBezierPath: dnaSequenceRect relativeCenterPosition: newGradientCenter];
    [[NSColor blackColor] set];
	[dnaSequenceRect stroke];
		///***********************************************************


	int i,cddi=0,blocksi=0,ucei=0;
	for (i=0; i<[NCUcdd count]; i++)
	{
		
		float protStart = [[[NCUcdd objectAtIndex:i] valueForKey:@"protStart"] floatValue];
		float protEnd = [[[NCUcdd objectAtIndex:i] valueForKey:@"protEnd"] floatValue];
		float myWidth = protEnd - protStart;
		NSBezierPath* testRect = [[[NSBezierPath alloc] init] autorelease];
		[testRect appendBezierPathWithRoundedRect:
		 NSMakeRect(topLineOffsetx/2.0, seqSizeY +10 + (cddi++)*4 , myWidth, 4 ) xRadius:2.5 yRadius:2.5];
		[testRect closePath];
		[testRect setLineJoinStyle:NSRoundLineJoinStyle];
		pt.x -= (protStart/NCULength)*seqSizeX;
		
		if ([testRect containsPoint:pt])
		{
			[NCUTextView setSelectedRange:NSMakeRange(protStart,myWidth)];
			[testRect setLineWidth: 4.5];
			
//			[CDDController removeSelectedObjects:[CDDController selectedObjects]];
			[CDDController setSelectedObjects:NCUcdd];
		}
		else
			[testRect setLineWidth: 0.1];
		
		pt.x += (protStart/NCULength)*seqSizeX;
		
		NSColor *testBackgroundColor = [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:1.0 alpha: 0.5];
		//NSGradient *testBackgroundGradient = [[NSGradient alloc]
		//									  initWithColorsAndLocations:
		//									  [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
		//									  testBackgroundColor, 0.7, testBackgroundColor, 1.0,  
		//									  nil];
		id tempTrans = [NSAffineTransform transform];		
		[tempTrans translateXBy:(protStart/NCULength)*seqSizeX yBy:0];
		[tempTrans concat];
		//NSPoint testGradientCenter = 
		//[[[NSAffineTransform transform]
		//  mapFrom:[testRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
		//[testBackgroundGradient drawInBezierPath: testRect relativeCenterPosition: testGradientCenter];
		[testBackgroundColor set];
		[testRect fill];
		[testRect stroke];
		[tempTrans invert];
		[tempTrans concat];

	}
	for (i=0; i<[NCUblocks count]; i++)
	{
		
		int protStart = [[[NCUblocks objectAtIndex:i] valueForKey:@"protStart"] integerValue];
		int protEnd = [[[NCUblocks objectAtIndex:i] valueForKey:@"protEnd"] integerValue];
		float myWidth = protEnd - protStart;

		NSBezierPath* testRect = [[[NSBezierPath alloc] init] autorelease];
		[testRect appendBezierPathWithRoundedRect:
		 NSMakeRect(topLineOffsetx/2.0, seqSizeY - 8 - (blocksi++)*4 , myWidth, 4) xRadius:2.5 yRadius:2.5];
		[testRect closePath];
		[testRect setLineJoinStyle:NSRoundLineJoinStyle];
		pt.x -= (protStart/NCULength)*seqSizeX;
		
		if ([testRect containsPoint:pt])
		{
			[NCUTextView setSelectedRange:NSMakeRange(protStart,myWidth)];
			[testRect setLineWidth: 4.5];
			
		//	[BlocksController removeSelectedObjects:[BlocksController selectedObjects]];
			[BlocksController setSelectedObjects:NCUcdd];
		}
		else
			[testRect setLineWidth: 0.1];
		
		pt.x += (protStart/NCULength)*seqSizeX;

		NSColor *testBackgroundColor = [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha: 0.5];
		//NSGradient *testBackgroundGradient = [[NSGradient alloc]
		//									  initWithColorsAndLocations:
		//									  [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
		//									  testBackgroundColor, 0.7, testBackgroundColor, 1.0,  
		//									  nil];
		id tempTrans = [NSAffineTransform transform];		
		[tempTrans translateXBy:(protStart/NCULength)*seqSizeX yBy:0];
		[tempTrans concat];
		
		//NSPoint testGradientCenter = 
		//[[[NSAffineTransform transform]
		//  mapFrom:[testRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
		//[testBackgroundGradient drawInBezierPath: testRect relativeCenterPosition: testGradientCenter];
		[testBackgroundColor set];
		[testRect fill];
		[testRect stroke];
		
		[tempTrans invert];
		[tempTrans concat];
	}
	for (i=0; i<[NCUuce count]; i++)
	{
		
		int protStart = [[[NCUuce objectAtIndex:i] valueForKey:@"protStart"] integerValue];
		int protEnd = [[[NCUuce objectAtIndex:i] valueForKey:@"protEnd"] integerValue];
		float myWidth = protEnd - protStart;

		NSBezierPath* testRect = [[[NSBezierPath alloc] init] autorelease];
		[testRect appendBezierPathWithRoundedRect:
		 NSMakeRect(topLineOffsetx/2.0, seqSizeY - 8 - (ucei++)*4 , myWidth, 4) xRadius:2.5 yRadius:2.5];
		[testRect closePath];
		[testRect setLineJoinStyle:NSRoundLineJoinStyle];
		pt.x -= (protStart/NCULength)*seqSizeX;
		
		if ([testRect containsPoint:pt])
		{
			[NCUTextView setSelectedRange:NSMakeRange(protStart,myWidth)];
			[testRect setLineWidth: 4.5];
			//[UCEController removeSelectedObjects:[UCEController selectedObjects]];
			[UCEController setSelectedObjects:NCUcdd];
		}
		else
			[testRect setLineWidth: 0.1];
		
		pt.x += (protStart/NCULength)*seqSizeX;
		
		NSColor *testBackgroundColor = [NSColor colorWithCalibratedRed:0.0 green:0.7 blue:0.0 alpha: 0.5];
		//NSGradient *testBackgroundGradient = [[NSGradient alloc]
		//									  initWithColorsAndLocations:
		//									  [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
		//									  testBackgroundColor, 0.7, testBackgroundColor, 1.0,  
		//									  nil];
				id tempTrans = [NSAffineTransform transform];		
				[tempTrans translateXBy:(protStart/NCULength)*seqSizeX yBy:0];
				[tempTrans concat];
		
		//NSPoint testGradientCenter = 
		//[[[NSAffineTransform transform]
		//  mapFrom:[testRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
		//[testBackgroundGradient drawInBezierPath: testRect relativeCenterPosition: testGradientCenter];
		[testBackgroundColor set];
		[testRect fill];
		[testRect stroke];
		
		[tempTrans invert];
		[tempTrans concat];
	}

//	[self setNeedsDisplay:YES];
// Begin to import clusters here?>....nah....thats when we input data
	
}

- (void) drawMe:(NSTimer *)timer;
{
	[self setNeedsDisplay:YES];
}
-(void)flagsChanged:(NSEvent *)theEvent
{
	NSLog(@"You just Changed the flags");
	
}
-(void)keyDown:(NSEvent *)theEvent
{
    NSString *characters = [theEvent characters];
    if ([characters length]) {
        unichar character = [characters characterAtIndex:0];
		NSLog(@"%c",character);
		switch (character) {
			case 'h':
				// toggle help
				NSLog(@"Howdy!");
				[self setNeedsDisplay: YES];
				break;
			case 'c':
				// toggle caps
				NSLog(@"Howdy!again!");
				[self setNeedsDisplay: YES];
				break;
				
		}
	}
}

- (void)setLevelForMouse:(NSPoint) local_point {

	float clicked_angle = atanf( (local_point.y - iCenterPt.y) / (local_point.x - iCenterPt.x) ) * (180/pi);
	

	if ( local_point.x < iCenterPt.x ) clicked_angle += 180;
	
	if (clicked_angle > iEndAngle)
		clicked_angle = iEndAngle;
	else if (clicked_angle < iStartAngle)
		clicked_angle = iStartAngle;
	
	float newLevel = (iEndAngle-clicked_angle)/(iEndAngle-iStartAngle) * 100.0;
	if ([self speed] != newLevel) {
		[self setSpeed: newLevel];
	};
}

- (BOOL)mouseDownCanMoveWindow {
	
	return NO;	
	
}

- (void)mouseDown:(NSEvent *)theEvent {
	NSPoint local_point; 
	if ([theEvent modifierFlags] & NSControlKeyMask) // send to pan
		NSLog(@"you pressed the NSControlKeyMask");
	else if ([theEvent modifierFlags] & NSAlternateKeyMask) // send to dolly
		NSLog(@"you pressed the NSAlternateKeyMask");
	else {
		local_point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	}
	
//	NSLog(@"DNAView:Selection:=%@",[[NCUController selectedObjects] description]);
	//myNCUs = [managedObjectContext executeFetchRequest:ncuFetch error:nil];
	//myBlocks = [managedObjectContext executeFetchRequest:blocksFetch error:nil];
	//myCDDs = [managedObjectContext executeFetchRequest:cddFetch error:nil];
	//myUCEs = [managedObjectContext executeFetchRequest:uceFetch error:nil];
	//NSLog(@"DNAView: %i,%i,%i,%i",[myNCUs count],[myBlocks count],[myCDDs count],[myUCEs count]);

	[self setLevelForMouse:local_point];
	
}

- (IBAction)resetView:(id)sender
{
	mouseScrollX = 0;
	mouseScrollY = 0;
}
- (void)scrollWheel:(NSEvent *)theEvent
{
	mouseScrollX -= [theEvent deltaX];
	mouseScrollY += [theEvent deltaY];
	
}

- (void)mouseEntered:(NSEvent *)theEvent
{
	NSPoint local_point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	NSLog(@"you point %f,%f",local_point.x,local_point.y);
}
- (void)mouseDragged:(NSEvent *)theEvent {
	NSPoint local_point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	
	[self setLevelForMouse:local_point];
	
}



@end





